package bw.hackathon.ub;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import bw.hackathon.ub.LaunchPage.CreateNewProduct;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Add_edit_patient extends Activity{
	
	private EditText enterName;
	private EditText enterDOB;
	private EditText enterPhoneNum;
	private EditText enterEmail;
	private EditText physAd;
	private ProgressDialog pDialog;
	JSONParser jsonParser = new JSONParser();
	private static String url_create_product = "http://www.tsbayford.com/android_connect/create_patient.php";
	private static final String TAG_SUCCESS = "success";
	
	public void onCreate(Bundle savedInstanceState) 
	   {
	      super.onCreate(savedInstanceState); // call super's onCreate
	      setContentView(R.layout.add_edit_patient); // inflate the UI
	      
	      enterName = (EditText) findViewById(R.id.patient_name);
	      enterDOB = (EditText) findViewById(R.id.patient_DOB);
	      enterPhoneNum = (EditText) findViewById(R.id.patient_Num);
	      enterEmail = (EditText) findViewById(R.id.patient_email);
	      physAd = (EditText) findViewById(R.id.patient_add);
	      
	      Bundle extras = getIntent().getExtras(); // get Bundle of extras
	      // if there are extras, use them to populate the EditTexts
	      // Bundle is used to send data to another activity
	 	 
	      if (extras != null)
	      {
	         enterName.setText(extras.getString("name"));  
	         enterEmail.setText(extras.getString("emailaddr"));
	         physAd.setText(extras.getString("addr"));
	         enterPhoneNum.setText(extras.getString("phonenumber"));
	         enterDOB.setText(extras.getString("dob"));
	         url_create_product = "http://www.tsbayford.com/android_connect/edit_patient.php";
	      }
	      
	      
	      Button saveDetails = 
	    		  (Button) findViewById(R.id.save_button);
	      saveDetails.setOnClickListener(new OnClickListener()
	      {
	    	  public void onClick(View view){
	    		  new CreateNewProduct().execute();
	      }
	      });
	      
	   }
	class CreateNewProduct extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Add_edit_patient.this);
			pDialog.setMessage("Creating Product..");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Creating product
		 * */	
	protected String doInBackground(String... args) {
		String name = enterName.getText().toString();
		String email = enterEmail.getText().toString();
		String phone = enterPhoneNum.getText().toString();
		String dob = enterDOB.getText().toString();
		String Addr = physAd.getText().toString();

		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("name", name));
		params.add(new BasicNameValuePair("phone", phone));
		params.add(new BasicNameValuePair("email", email));
		params.add(new BasicNameValuePair("dob", dob));
		params.add(new BasicNameValuePair("addr", Addr));
		// getting JSON Object
		// Note that create product url accepts POST method
		JSONObject json = jsonParser.makeHttpRequest(url_create_product,
				"POST", params);
		
		// check log cat fro response
		Log.d("Create Response", json.toString());

		// check for success tag
		try {
			int success = json.getInt(TAG_SUCCESS);

			if (success == 1) {
				// successfully created product
				Intent i = new Intent(getApplicationContext(), TestReady.class);
				i.putExtra("message", "Patient Management Succeded/n Your Patient ID is"+json.getString("Id"));
				startActivity(i);
				
				// closing this screen
				finish();
			} else {
				// failed to create product
				Intent i1 = new Intent(getApplicationContext(), TestReady.class);
				i1.putExtra("message", "Connection Failure Please Try Again");
				startActivity(i1);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * After completing background task Dismiss the progress dialog
	 * **/
	protected void onPostExecute(String file_url) {
		// dismiss the dialog once done
		pDialog.dismiss();
	}	
	private void saveContact() 
	   {
	      // get DatabaseConnector to interact with the SQLite database
	      //DatabaseConnection databaseConnector = new DatabaseConnection(this);

	      // Check if the Intent contains any data.  If No add the data from the add_contact layout file
	      // Else update the data
	      if (getIntent().getExtras() == null)
	      {
	         // insert the student information into the database
	         //databaseConnector.insertContact(
	            //enterName.getText().toString(),
	           // enterEmail.getText().toString(), 
	            //enterPhoneNum.getText().toString(), 
	            //enterDOB.getText().toString(),
	            //physAd.getText().toString());
	      } // end if
	      else
	      {

	         //databaseConnector.updateContact(pat_ID,

	         //databaseConnector.updateContact(
	            //enterName.getText().toString(),
	            //enterEmail.getText().toString(), 
	            //enterPhoneNum.getText().toString(), 
	            //enterDOB.getText().toString(),
	            //physAd.getText().toString()));
	      } // end else
	   } // end class saveContact
}
}